package com.servlet;

import com.alibaba.fastjson.JSON;
import com.dao.Impl.NewsDaoImpl;
import com.dao.Impl.ResourceDaoImpl;
import com.dao.Impl.UserDaoImpl;
import com.dao.UserDao;
import com.entity.Resource;
import com.entity.Staff;
import com.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author jie
 */
@WebServlet(value = "/homeServlet/*")
public class HomeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methon = MyUtil.getMethon(request);
        String target = null;
        switch (methon) {
            case "showPower":
                target=showPower(request, response);
                break;
            case "exit":
                exit(request, response);
                break;
            case "showNews":
                target = showNews(request, response);
                break;
            default:
                break;
        }
        if (target != null) {
            request.getRequestDispatcher(target).forward(request, response);
        }
    }

    private String showPower(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(false);
        Object staff = session.getAttribute("staff");
        if (staff != null) {
            List<Resource> resList = new ResourceDaoImpl().findByStaffId((Staff) staff);
            request.setAttribute("resList", resList);
            return "/home/home.jsp";
        }
        return "/login/login.jsp";
    }

    private void exit(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        session.invalidate();
        response.sendRedirect("/login/login.jsp");
    }

    private String showNews(HttpServletRequest request, HttpServletResponse response) {
        List<Map> news = new NewsDaoImpl().findStatus();
        UserDao userDao =new UserDaoImpl();
        Map map = userDao.findsum();
        for (int i = 1; i <= 12 ; i++) {
            if (map.get(i) == null){
                map.put(i,0);
            }
        }
        request.setAttribute("umap",JSON.toJSONString(map));
        request.setAttribute("news", JSON.toJSONString(news));
        return "/home/homeIndex.jsp";
    }
}
